package com.justreading.netty.protobuftcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;

/**
 * @author LYJ
 * @Description
 * @date 2021 年 11 月 09 日 下午7:47
 */
public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        String message = new String(msg.getContent(), Charset.forName("utf-8"));
        System.out.println("客户端接收到消息=" + message);
        System.out.println();
        System.out.println("客户端接收消息数量=" + (++this.count));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 10; ++i) {
            String msg = "今天天气冷，吃烧烤";
            byte[] bytes = msg.getBytes(CharsetUtil.UTF_8);
            int len = bytes.length;
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setContent(bytes);
            messageProtocol.setLen(len);
            ctx.channel().writeAndFlush(messageProtocol);
        }
    }
}
